import type { RouteRecordRaw } from 'vue-router';

let firstMenu: any = null;

export function menuToRoute(menus: any[]): RouteRecordRaw[] {
  const newRoutes: RouteRecordRaw[] = [];

  // 1. 先筛选出所有的路由
  const allRoutes: RouteRecordRaw[] = [];
  const files = require.context('../router/main', true, /\.ts/);
  files.keys().forEach((path) => {
    // path 是 相对路径的   ./analysis/dashboard/dashboard.ts   通过split分割拿到中间路径即可
    // console.log(path);
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const file = require('../router/main' + path.split('.')[1]);
    allRoutes.push(file.default);
  });
  // console.log(allRoutes);

  // 2. 根据菜单获取对应的路由
  // type === 1  ==>  children
  // type === 2  ==>  url  ==> path
  const _recuren = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type == 2) {
        if (!firstMenu) firstMenu = menu;

        const route = allRoutes.find((route) => route.path === menu.url);
        route && newRoutes.push(route);
      } else {
        _recuren(menu.children);
      }
    }
  };
  _recuren(menus);

  return newRoutes;
}

import type { IBreadcrumb } from '@/components/nav-header/breadcrumb';
export function findMenuToBreadcrumb(routes: any[], targetPath: string) {
  // console.log(routes, targetPath);
  const breadcrumb: IBreadcrumb[] = [];
  findMenuToPath(routes, targetPath, breadcrumb);
  return breadcrumb;
}

export function findMenuToPath(
  routes: any[],
  targetPath: string,
  breadcrumb?: IBreadcrumb[],
): any {
  // console.log(routes, targetPath);
  for (const menu of routes) {
    if (menu.type === 1) {
      // 因为有的menu.children可能为空   以防后面报错
      const findMenu = findMenuToPath(menu.children ?? [], targetPath);
      if (findMenu) {
        breadcrumb?.push({ name: menu.name });
        breadcrumb?.push({ name: findMenu.name, path: findMenu.url });
        return findMenu;
      }
    } else if (menu.type === 2 && menu.url === targetPath) {
      return menu;
    }
  }
}

export { firstMenu };
